package com.java.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Scanner;

public class JDBCUtils {
	static Connection con;
	
	static String url = "jdbc:mysql://localhost:3306/database?serverTimezone=UTC";
	static String user = "root";
	static String password = "sysadmin";
	
	
	private static Connection getConn() {
		// 加载驱动类
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		}

		try {
			con = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {

			e.printStackTrace();
		} // 链接数据库
		return con;
	}
	
	public static int excuteUpdate(String sql,List<Object> params) {
		try {
			PreparedStatement ps = getConn().prepareStatement(sql);
			for(int i = 0;i<params.size();i++) {
				ps.setObject(i+1, params.get(i));
			}
			return ps.executeUpdate();
		}catch(SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public static ResultSet excuteQuery(String sql,List<Object> params) {
		try {
			PreparedStatement ps = getConn().prepareStatement(sql);
			if(params!=null) {
				for(int i = 0;i<params.size();i++) {
					ps.setObject(i+1, params.get(i));
				}
			}
			return ps.executeQuery();
		}catch(SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}
